package com.example.wificovv2;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;
import android.os.Bundle;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.view.*;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.widget.*;
import android.view.MenuItem;
import com.example.database.myDBHelper;
import com.example.wificov.Innitialvaluepic;
import com.example.wificov.Loadpicture;

public class Loadmap extends Activity {
	//khoi tao database
	myDBHelper db;
	
	int index=0;	
	GoogleMap googleMap;
    UiSettings uisetting;
    LatLng myLatlng;
	int locFlag = 1; 
	Marker marker;
	ArrayList<LatLng> markerPoints, mapPoints;
	private ArrayAdapter<String> mainAdapter = null;		
	ArrayList<String>array = new ArrayList<String>();
    
	// khai bao cac bien luu tru
	
	Button loadgoogle, savemapgoogle, saveApG, makerAPG, getnextG;
	EditText xmap, ymap, fileMapName, xAP,yAP, accesspointG;
	ListView listAp = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_loadmap);
		db = new myDBHelper(Loadmap.this);
		
		FragmentManager fragmentManager = getFragmentManager();
		MapFragment mapFragment = (MapFragment) fragmentManager.findFragmentById(R.id.loadgooglemap);		
		googleMap = mapFragment.getMap();
		
		// Khai bao cac doi tuong trong layout
		loadgoogle = (Button) findViewById(R.id.loadgoogle);
		xmap = (EditText) findViewById(R.id.xmap);
		ymap = (EditText) findViewById(R.id.ymap);		
		fileMapName = (EditText) findViewById(R.id.filemapname);
		savemapgoogle = (Button) findViewById(R.id.savemapgoogle);
		xAP = (EditText) findViewById(R.id.xApG);
		yAP = (EditText) findViewById(R.id.yApG);		
		accesspointG = (EditText) findViewById(R.id.accesspointG);
		listAp = (ListView) findViewById(R.id.listApG);			
		mainAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);	
		listAp.setAdapter(mainAdapter);
		saveApG = (Button) findViewById(R.id.saveApG);
		makerAPG = (Button) findViewById(R.id.makerAPG);
		getnextG = (Button) findViewById(R.id.getnextG);
		

		// Xu ly cac doi tuong
		// 1. Khi tuy chon loadgoogle duoc chon
		// Load map tu google vao Fragmnet
		loadgoogle.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// Getting reference to SupportMapFragment of the activity_main
		        MapFragment fm = (MapFragment)getFragmentManager().findFragmentById( R.id.loadgooglemap );		 
		        // Getting Map for the SupportMapFragment
		        googleMap = fm.getMap();		 
		        
		        // Enable MyLocation Button in the Map
		        googleMap.setMyLocationEnabled( true );
		        googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
		        uisetting = googleMap.getUiSettings();
		        uisetting.setZoomControlsEnabled( false );
		       
			}});
				
      //mMap.setMyLocationEnabled(true);
        googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {					
			@Override
			public void onMyLocationChange(Location arg0) {
				myLatlng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
				if(locFlag == 1)
				{
					googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatlng, 16));					
					locFlag = 0;
					double x = myLatlng.latitude;
					double y = myLatlng.longitude;
					xmap.setText(String.valueOf(x));
					ymap.setText(String.valueOf(y));
				}
			}
		});
        
     // Setting onclick event listener for the map
        this.googleMap.setOnMapClickListener(new OnMapClickListener() {
        		 
                @Override
                public void onMapClick(LatLng point) {                	
                	// Adding new item to the ArrayList
                    markerPoints.add(point);   
                    drawStartStopMarkers(point);
                    LatLng origin = markerPoints.get(0);
                    double x = origin.latitude;
					double y = origin.longitude;
					xAP.setText(String.valueOf(x));
					yAP.setText(String.valueOf(y));  
                	// Already two locations
                    if(markerPoints.size()>1 ){
                    	markerPoints.clear();
                    	marker.remove();           
                    	
                    }  
//                    MotionEvent event;
//                    GeoPoint p = null;
//                       if (event.getAction() == MotionEvent.ACTION_UP) {
//                    	   p = mapFragment.getProjection().fromPixels((int) event.getX(),(int) event.getY());
//                    	   xAP.setText(p.getLatitudeE6() / 1E6 + "Action is : "+ event.getAction());
//                    	   yAP.setText(p.getLongitudeE6() / 1E6 + "Action is : "+ event.getAction());
//                    	   return true;
//                    	   }
//                       return false;
//                       }	        
                }});
        googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {			
			@Override
			public boolean onMarkerClick(Marker arg0) {
				LatLng title = ReverseGeocodingTask(arg0.getPosition());			
				return false;
			}
			protected LatLng ReverseGeocodingTask(LatLng params) {
	        double latitude = params.latitude;
	        double longitude = params.longitude;
			return params;	
	        
			} 
		});
        
		// Luu vao database
        saveApG.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
					//luu toa do da load					
					String MapName = fileMapName.getText().toString();					
					int mapId = db.getMapId(MapName);
					db.addAPLocation(mapId, accesspointG.getText().toString(), 
							Float.parseFloat(xAP.getText().toString()), 
							Float.parseFloat(yAP.getText().toString()));
					//Sau khi update thì xóa trắng dữ liệu 
					 accesspointG.setText("");
					 accesspointG.requestFocus();
			}
		});
        
        // Luu vao database
        savemapgoogle.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
					//luu toa do da load
					db.addMapInfor(fileMapName.getText().toString(),
							Float.parseFloat(xmap.getText().toString()), 
							Float.parseFloat(ymap.getText().toString()), 0, 0);
			}
		});
        
		//Đánh dấu điểm chọn trên map
		makerAPG.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				//Add tên AP vào listview
				String name = accesspointG.getText().toString();
				//Đưa vào danh sách
				array.add(name);
				//cập nhật giao diện
				mainAdapter.notifyDataSetChanged();									
				
				//Đánh dấu vị trí các AP trên map
				float x;
			    float y;
				x = Float.parseFloat(xAP.getText().toString());
			    y = Float.parseFloat(yAP.getText().toString());
			    
//			    LatLng coords = mapFragment.getMap().getProjection().fromScreenLocation(point);
			 // lay du lieu tren 2 textview long and lat danh dau tren map
				MarkerOptions marker = new MarkerOptions();
				LatLng latlng = new LatLng(Double.parseDouble(xAP.getText().toString()), Double.parseDouble(yAP.getText().toString()));
				marker.position(latlng);
				marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
				googleMap.addMarker(marker);
			}
		});
		
		// Chuyen sang Activity Innitialvalue
		getnextG.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if( xAP.getText().toString().equals("") || yAP.getText().toString().equals("") )
					Toast.makeText( Loadmap.this, "Nhap it nhat toa do cua it nhat mot AP", Toast.LENGTH_SHORT).show();
				else{
					Intent intent = new Intent(Loadmap.this, Innitialvaluemap.class);
					int mapId = db.getMapId(fileMapName.getText().toString());
					intent.putExtra("mapid", mapId);
					startActivity(intent);}
			}
		});

	}
	
	// Drawing Start and Stop locations
    private void drawStartStopMarkers(LatLng point){
    	// Creating MarkerOptions
        MarkerOptions options = new MarkerOptions();
        // Setting the position of the marker
        options.position(point);        
        // Add new marker to the Google Map Android API V2    	
    		options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            marker = googleMap.addMarker(options);    	
    	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		
	};
	
	protected void setContentView(MapFragment mapFragment) {
		// TODO Auto-generated method stub
		
	}

}
